package org.spider.parse;

import org.spider.model.ExtractRule;
import org.spider.model.ResultItems;
import org.spider.selector.Html;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 15911
 */
public abstract class AbstractDefaultParse {

    public List<ResultItems> parse(String htmlstr, List<ExtractRule> extractRules) {
        Html html = new Html(htmlstr);
        return parse(html, extractRules);
    }

    public List<ResultItems> parse(String htmlstr, String baseUrl, List<ExtractRule> extractRules) {
        Html html = new Html(htmlstr, baseUrl);
        return parse(html, extractRules);
    }

    private List<ResultItems> parse(Html html, List<ExtractRule> extractRules) {
        List<ResultItems> resultItemsList = new ArrayList<>();
        for (ExtractRule extractRule: extractRules) {
            ResultItems resultItems = new ResultItems();
            BeanUtils.copyProperties(extractRule, resultItems);
            if (extractRule.isMulti()) {
                List<String> results = html.selectDocumentForList(extractRule.getSelector());
                if (extractRule.isNotNull() && CollectionUtils.isEmpty(results)) {
                    resultItems.failed();
                } else {
                    resultItems.setFieldValue(results);
                }
            } else {
                String result = html.selectDocument(extractRule.getSelector());
                if (extractRule.isNotNull() && result == null) {
                    resultItems.failed();
                } else {
                    resultItems.setFieldValue(result);
                }
            }
            resultItemsList.add(resultItems);
        }
        return resultItemsList;
    }
}
